var current_year;
var current_month = "all";
const tableName = {
    encryption: "加密",
    decryption: "解密",
    signature: "签名",
    verification: "验证",
    signcryption: "签密",
    unsigncryption: "解签密",
    mac: "MAC",
    authenticated_encryption: "认证加密",
    decryption_verification: "解密验证"
};
var data = [];
var current_item = "operator";
var current_legend = "操作人";
var current_chart = "bar_chart";
var flag = false;
var myEcharts;

$(function () {
    var chart = $('input[name="chart_type"]');

    chart.on('ifChecked', function () {
        refresh_chart();
    });

    chart.iCheck({
        checkboxClass: 'icheckbox_minimal-grey',
        radioClass: 'iradio_minimal-grey',
        increaseArea: '20%'
    });

    $('#cartogram').on("click", get_common_diagram);
    $('#sequence_diagram').on("click", get_series_diagram);

    getDimension();
    init_year_input();
});

function init_year_input() {
    var date = new Date();
    var current = date.getFullYear();
    $('#year_input').val(current);
}

function get_common_diagram() {
    var start_time = $('#dtp_start').val();
    var end_time = $('#dtp_end').val();
    var operator = $('#operator_input').val();
    var table = $('#table_input').val();

    if (start_time === "" || end_time === "") {
        window.wxc.xcConfirm("选择时间段", window.wxc.xcConfirm.typeEnum.error);
        return;
    }

    $.ajax({
        url: 'servlet/CountServlet',
        type: 'post',
        data: {
            start: start_time,
            end: end_time,
            operator: operator,
            table: table
        },
        dataType: 'json',
        success: function (json) {
            data = json;
            $('.switch-area').removeClass('none');
            refresh_chart();
        },
        error: function () {
            window.wxc.xcConfirm("生成统计图失败", window.wxc.xcConfirm.typeEnum.error);
        }
    });
}

function get_series_diagram() {
    var start_time = $('#dtp_start').val();
    var end_time = $('#dtp_end').val();
    var operator = $('#operator_input').val();
    var table = $('#table_input').val();

    if (start_time === "" || end_time === "") {
        window.wxc.xcConfirm("选择时间段", window.wxc.xcConfirm.typeEnum.error);
        return;
    }

    $.ajax({
        url: 'servlet/SeriesServlet',
        type: 'post',
        data: {
            start: start_time,
            end: end_time,
            operator: operator,
            span: 'day',
            table: table
        },
        success: function (json) {
            json = eval("(" + json + ")");
            var line_data;
            for (var key in json) {
                line_data = json[key];
                if (flag) {
                    draw_line_echarts(line_data);
                } else {
                    draw_line_highchart(line_data);
                }
            }
        },
        error: function () {
            window.wxc.xcConfirm("生成序列图失败", window.wxc.xcConfirm.typeEnum.error);
        }
    });
}

function get_stack_diagram(month) {
    current_year = $('#year_input').val();

    $.ajax({
        url: 'servlet/StackServlet',
        type: 'post',
        data: {
            year: current_year,
            month: month
        },
        dataType: 'json',
        success: function (json) {
            draw_stack_echarts(json);
        },
        error: function () {
            window.wxc.xcConfirm("生成堆积图失败", window.wxc.xcConfirm.typeEnum.error);
        }
    })
}

function refresh_chart() {
    current_item = $("input[name='dimension']:checked").val();
    current_legend = $('input[name="dimension"]:checked').parent().next().html();
    current_chart = $('input[name="chart_type"]:checked').val();
    var option = {};
    if (flag) {//使用echarts
        if (current_chart === 'bar_chart') {
            option = get_bar_echarts();
        } else if (current_chart === 'pie_chart') {
            option = get_pie_echarts();
        }
        echarts.dispose(document.getElementById('main'));
        myEcharts = echarts.init(document.getElementById('main'));
        myEcharts.setOption(option, true, false);
    } else {//使用highcharts
        if (current_chart === 'bar_chart') {
            option = get_bar_highchart();
        } else if (current_chart === 'pie_chart') {
            option = get_pie_highchart();
        }
        $('#main').highcharts(option);
    }
}

function get_bar_echarts() {
    var categories = [];
    var data_series = [];
    outer:
        for (var i = 0; i < data.length; i++) {
            for (var key in data[i]) {
                if (key === current_item) {
                    for (var item in data[i][key]) {
                        categories.push(item);
                        data_series.push(data[i][key][item]);
                    }
                    break outer;
                }
            }
        }

    var title = {
        text: '审计数据柱形统计',
        textStyle: {
            fontWeight: 'lighter',
            fontSize: 20
        },
        right: 'center'
    };
    var tooltip = {
        trigger: 'axis',
        formatter: '数量:{c0}'
    };
    var xAxis = {
        type: 'category',
        nameLocation: 'middle',
        nameGap: 40,
        nameTextStyle: {
            fontWeight: 'bold',
            fontSize: 15
        },
        data: categories,
        axisLine: {
            onZero: false,
            lineStyle: {
                width: 3
            }
        },
        axisTick: {
            show: false
        },
        axisLabel: {
            margin: 10,
            textStyle: {
                fontWeight: 'bold'
            }
        },
        offset: 1
    };
    var yAxis = {
        name: '数\n量',
        nameLocation: 'middle',
        nameGap: 40,
        nameTextStyle: {
            fontWeight: 'bold',
            fontSize: 15
        },
        axisTick: {
            show: false
        },
        nameRotate: 0,
        axisLine: {
            onZero: false,
            lineStyle: {
                width: 3
            }
        },
        axisLabel: {
            margin: 10,
            textStyle: {
                fontWeight: 'bold'
            }
        }
    };
    var series = [{
        type: 'bar',
        data: data_series,
        itemStyle: {
            normal: {
                color: function (params) {
                    var colorList = [
                        '#c23531', '#2f4554', '#61a0a8',
                        '#d48265', '#91c7ae', '#749f83',
                        '#ca8622', '#bda29a', '#6e7074',
                        '#546570', '#c4ccd3'
                    ];
                    return colorList[params.dataIndex]
                }
            }
        },
        barMaxWidth: '40px',
        label: {
            normal: {
                show: true,
                position: 'top',
                formatter: '{c}'
            }
        }
    }];
    var json = {};
    json.title = title;
    json.tooltip = tooltip;
    json.xAxis = xAxis;
    json.yAxis = yAxis;
    json.series = series;
    return json;
}

function get_pie_echarts() {
    var categories = [];
    var data_series = [];
    outer:
        for (var i = 0; i < data.length; i++) {
            for (var key in data[i]) {
                if (key === current_item) {
                    for (var item in data[i][key]) {
                        categories.push(item);
                        data_series.push({
                            'value': data[i][key][item],
                            'name': item
                        });
                    }
                    break outer;
                }
            }
        }

    var title = {
        text: '审计数据饼形统计',
        textStyle: {
            fontWeight: 'lighter',
            fontSize: 20
        },
        left: 'center'
    };
    var tooltip = {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
    };
    var legend = {
        orient: 'vertical',
        left: '10%',
        top: '10%',
        data: categories
    };
    var series = [
        {
            name: '数量',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: data_series,
            label: {
                normal: {
                    position: 'outside',
                    textStyle: {
                        fontSize: 17
                    }
                }
            },
            itemStyle: {
                emphasis: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }
    ];
    var json = {};
    json.title = title;
    json.tooltip = tooltip;
    json.legend = legend;
    json.series = series;
    return json;
}

function draw_line_echarts(data) {
    $('.switch-area').addClass('none');
    var categories = [];
    var data_series = [];
    for (var key in data) {
        categories.push(key);
        data_series.push(data[key]);
    }
    var option = {
        title: {
            text: '审计数据折线统计',
            textStyle: {
                fontWeight: 'lighter',
                fontSize: 20
            },
            left: 'center'
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['数量'],
            right: 'right'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            boundaryGap: false,
            data: categories
        }],
        yAxis: [{
            name: '数量',
            type: 'value'
        }],
        series: [{
            name: '数量',
            type: 'line',
            stack: '总量',
            areaStyle: {normal: {}},
            data: data_series
        }]
    };
    echarts.dispose(document.getElementById('main'));
    myEcharts = echarts.init(document.getElementById('main'));
    myEcharts.setOption(option, true, false);
}

function get_bar_highchart() {
    var categories = [];
    var data_series = [];
    outer:
        for (var i = 0; i < data.length; i++) {
            for (var key in data[i]) {
                if (key === current_item) {
                    for (var item in data[i][key]) {
                        categories.push(item);
                        data_series.push(data[i][key][item]);
                    }
                    break outer;
                }
            }
        }

    var chart = {
        renderTo: 'container',
        type: 'bar',
        margin: 75,
        options3d: {
            enabled: true,
            alpha: 15,
            beta: 15,
            depth: 50,
            viewDistance: 25
        }
    };
    var title = {
        text: '审计数据柱形统计'
    };
    var legend = {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'middle',
        borderWidth: 0
    };
    var tooltip = {
        borderRadius: 10,             // 边框圆角
        animation: true,
        formatter: function () {
            return '<b>' + this.series.name + '</b><br/>' + this.x + ': ' + this.y;
        }
    };
    var plotOptions = {
        bar: {
            depth: 25,
            maxPointWidth: 50
        }
    };
    var xAxis = {
        categories: categories
    };
    var yAxis = {
        allowDecimals: false,
        min: 0,
        title: {
            text: '数量'
        }
    };
    var series = [{
        name: current_legend,
        data: data_series
    }];

    var json = {};
    json.chart = chart;
    json.legend = legend;
    json.title = title;
    json.tooltip = tooltip;
    json.xAxis = xAxis;
    json.yAxis = yAxis;
    json.series = series;
    json.plotOptions = plotOptions;
    return json;
}

function get_pie_highchart() {
    var data_series = [];
    outer:
        for (var i = 0; i < data.length; i++) {
            for (var key in data[i]) {
                if (key === current_item) {
                    for (var item in data[i][key]) {
                        var array = [];
                        array.push(item);
                        array.push(data[i][key][item]);
                        data_series.push(array);
                    }
                    break outer;
                }
            }
        }

    var chart = {
        type: 'pie',
        options3d: {
            enabled: true,
            alpha: 45,
            beta: 0
        }
    };
    var title = {
        text: '审计数据饼形统计'
    };
    var tooltip = {
        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
    };

    var plotOptions = {
        pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            depth: 35,
            dataLabels: {
                enabled: true,
                format: '{point.name}'
            }
        }
    };
    var series = [{
        type: 'pie',
        name: 'number',
        colorByPoint: true,
        data: data_series
    }];

    var json = {};
    json.chart = chart;
    json.title = title;
    json.tooltip = tooltip;
    json.plotOptions = plotOptions;
    json.series = series;
    json.exporting = {
        enabled: true
    };
    return json;
}

function draw_line_highchart(data) {
    $('.switch-area').addClass('none');
    var series_data = [];
    for (var key in data) {
        var item = [];
        var date = key.split("-", 3);
        item.push(Date.UTC(date[0], date[1], date[2]));
        item.push(data[key]);
        series_data.push(item);
    }
    var chart = {
        zoomType: 'x'
    };
    var title = {
        text: '审计数据折线统计'
    };
    var xAxis = {
        type: 'datetime',
        dateTimeLabelFormats: {
            millisecond: '%H:%M:%S.%L',
            second: '%H:%M:%S',
            minute: '%H:%M',
            hour: '%H:%M',
            day: '%m-%d',
            week: '%m-%d',
            month: '%Y-%m',
            year: '%Y'
        }
    };
    var tooltip = {
        dateTimeLabelFormats: {
            millisecond: '%H:%M:%S.%L',
            second: '%H:%M:%S',
            minute: '%H:%M',
            hour: '%H:%M',
            day: '%Y-%m-%d',
            week: '%m-%d',
            month: '%Y-%m',
            year: '%Y'
        }
    };
    var legend = {
        enabled: false
    };
    var plotOptions = {
        area: {
            fillColor: {
                linearGradient: {
                    x1: 0,
                    y1: 0,
                    x2: 0,
                    y2: 1
                },
                stops: [
                    [0, Highcharts.getOptions().colors[0]],
                    [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
                ]
            },
            marker: {
                radius: 2
            },
            lineWidth: 1,
            states: {
                hover: {
                    lineWidth: 1
                }
            },
            threshold: null
        }
    };
    var series = [{
        type: 'area',
        name: '数量',
        data: series_data
    }];
    var json = {};
    json.chart = chart;
    json.title = title;
    json.xAxis = xAxis;
    json.tooltip = tooltip;
    json.legend = legend;
    json.plotOptions = plotOptions;
    json.series = series;

    $('#main').highcharts(json);
}

function draw_stack_echarts(json) {
    echarts.dispose(document.getElementById('main'));
    myEcharts = echarts.init(document.getElementById('main'));
    var title;
    var xAxis_name;
    if (current_month === "all") {
        title = current_year + "年日志数据统计";
        myEcharts.on('click', function (object) {
            var name = object.name;
            current_month = name;
            name = name.substring(0, name.length - 1);
            get_stack_diagram(name);
        });
        xAxis_name = "月份";
    } else {
        title = current_year + "年" + current_month + "日志数据月份统计";
        xAxis_name = "天";
    }
    var legend = [];
    for (var key in tableName) {
        legend.push(tableName[key]);
    }
    legend.push("总数");
    var option = {
        title: {
            text: title,
            left: 'center',
            textStyle: {
                fontSize: '22'
            }
        },
        tooltip: {
            trigger: "axis",
            axisPointer: {
                type: "shadow",
                textStyle: {
                    color: "#fff"
                }
            }
        },
        grid: {
            borderWidth: 0,
            top: 110,
            bottom: 95,
            textStyle: {
                color: "#fff"
            }
        },
        legend: {
            right: '10%',
            top: '10%',
            data: legend
        },
        toolbox: {
            show: true,
            feature: {
                dataView: {},
                restore: {},
                saveAsImage: {
                    pixelRatio: 2
                },
                myTool: {
                    show: true,
                    title: '返回',
                    icon: 'image://img/return.svg',
                    onclick: function () {
                        current_month = "all";
                        get_stack_diagram(current_month);
                    }
                }
            }
        },
        calculable: true,
        xAxis: [{
            type: "category",
            name: xAxis_name,
            axisLine: {
                lineStyle: {
                    color: '#90979c'
                }
            },
            splitLine: {
                "show": false
            },
            axisTick: {
                "show": false
            },
            splitArea: {
                "show": false
            },
            axisLabel: {
                "interval": 0
            },
            data: get_category(json)
        }],
        yAxis: [{
            type: "value",
            name: "数量",
            splitLine: {
                show: false
            },
            axisLine: {
                lineStyle: {
                    color: '#90979c'
                }
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                interval: 10
            },
            splitArea: {
                show: false
            }
        }],
        dataZoom: [{
            show: true,
            height: 30,
            xAxisIndex: [0],
            bottom: 30,
            handleSize: '110%'
        }, {
            type: "inside",
            show: true,
            height: 15,
            start: 1,
            end: 35
        }],
        series: get_element(json)
    };
    myEcharts.setOption(option, true, false);
}

function get_element(json) {
    var series = [];
    var length = json.length;
    for (var i = 0; i < length; i++) {
        var data = [];
        var name = "";
        var elment = json[i];
        for (var key in elment) {
            if (elment.hasOwnProperty(key)) {
                name = tableName[key]; //获取表格名
                var list = elment[key]; //数据集合
                var item_list = [];
                for (var item in list) {
                    if (list.hasOwnProperty(item)) {
                        item_list.push(item);
                    }
                }
                item_list.sort();
                var len = item_list.length;
                var temp;
                for (var k1 = 0; k1 < len; k1++) {
                    temp = item_list[k1];
                    data.push(list[temp]);
                }
            }
        }
        var option = {
            name: name,
            type: "bar",
            stack: "总量",
            barMaxWidth: 35,
            barGap: "10%",
            itemStyle: {
                normal: {
                    label: {
                        show: true,
                        textStyle: {
                            color: "#fff"
                        },
                        position: "insideTop",
                        formatter: function (p) {
                            return p.value > 0 ? (p.value) : '';
                        }
                    }
                }
            },
            data: data
        };
        series.push(option);
    }
    var sum_data = [];
    var number = series[0].data.length;
    for (var j = 0; j < number; j++) {
        var result = 0;
        for (var k = 0; k < length; k++) {
            result += series[k].data[j];
        }
        sum_data.push(result);
    }
    var sum = {
        name: "总数",
        type: "line",
        symbolSize: 10,
        symbol: 'circle',
        itemStyle: {
            normal: {
                barBorderRadius: 0,
                label: {
                    show: true,
                    position: "top",
                    formatter: function (p) {
                        return p.value > 0 ? (p.value) : '';
                    }
                }
            }
        },
        data: sum_data
    };
    series.push(sum);
    return series;
}

function get_category(json) {
    var category = [];
    var elment = json[0];
    for (var key in elment) {
        var list = elment[key];
        for (var item in list) {
            category.push(item);
        }
    }
    category.sort();
    return category;
}

function getDimension() {
    var area = $('.dimension-area');
    area.html('');
    var title = $('<span>');
    title.html('统计维度');
    area.append(title);
    var counter = 0;
    $.ajax({
        url: 'servlet/DimensionServlet',
        type: 'get',
        success: function (data) {
            var json = eval("(" + data + ")");
            for (var key in json) {
                var input = $('<input>');
                input.attr('type', 'radio');
                input.attr('name', 'dimension');
                input.attr('id', key);
                input.attr('value', key);
                if (counter === 0) {
                    input.iCheck('check');
                }
                input.appendTo(area);
                var label = $('<label>');
                label.attr('for', key);
                label.html(json[key]);
                label.appendTo(area);
                counter++;
            }
            var dimension = $('input[name="dimension"]');
            dimension.on('ifChecked', function () {
                refresh_chart();
            });
            dimension.iCheck({
                checkboxClass: 'icheckbox_minimal-grey',
                radioClass: 'iradio_minimal-grey',
                increaseArea: '20%'
            });
        },
        error: function () {
            window.wxc.xcConfirm("初始化统计维度失败", window.wxc.xcConfirm.typeEnum.error);
        }
    })
}
